import React from "react";
import { Tag, Space, Card } from "antd";
import { useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { setSelectedKeys, removeTag, removeAllTags } from "@/store/menuSlice";
import { RootState } from "@/store/store";
import "./tag.scss";

const TagCom = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { selectedKeys, tagList } = useSelector(
    (state: RootState) => state.menu
  );

  const handleTagClick = (path: string) => {
    navigate(path);
    dispatch(setSelectedKeys([path]));
    sessionStorage.setItem("selectedKeys", JSON.stringify([path]));
  };

  const clickHome = () => {
    handleTagClick("home");
  };
  const clickCloseTag = (key: string) => () => {
    dispatch(removeTag(key));
  };
  const clickCloseAll = () => {
    dispatch(removeAllTags());
  };

  const selectedPath = selectedKeys[0];

  return (
    <>
      <div
        style={{
          width: "100%",
          display: "flex",
          height: "40px",
          justifyContent: "space-between",
          alignItems: "center",
        }}
      >
        <Space className="tag-box" size={[0, 8]} wrap>
          {/* 首页标签 */}
          <Tag
            onClick={clickHome}
            color={selectedPath === "home" ? "#1890ff" : undefined}
            className="Tag"
          >
            首页
          </Tag>

          {/* 动态生成的最底层标签 */}

          {tagList.map((item: any) => (
            <Tag
              className="Tag"
              closeIcon
              color={selectedPath === item.key ? "#1890ff" : undefined}
              key={item.key}
              onClick={() => handleTagClick(item.key)}
              onClose={clickCloseTag(item.key)}
            >
              {item.name}
            </Tag>
          ))}
        </Space>
        <Space>
          {/* 关闭所有标签 */}
          {tagList.length !== 0 && (
            <Tag
              className="Tag"
              color="#cd201f"
              onClick={clickCloseAll}
              style={{ margin: "16px 0" }}
            >
              关闭所有
            </Tag>
          )}
        </Space>
      </div>
    </>
  );
};

export default TagCom;
